package com.hqm.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hqm.meta.PictureUploadMsg;
import com.hqm.meta.UploadMsg;
import com.hqm.service.PictureService;

@Controller
public class PictureController {

	private static final Log logger = LogFactory.getLog(PictureController.class);
	
	@Resource
	private PictureService pictureService;
	
	/**
	 * 处理图片上传
	 * @param multipartFile
	 * @return UploadMsg
	 */
	@ResponseBody
	@RequestMapping(value = "/api/upload", method = RequestMethod.POST)
	public UploadMsg iconUpload(@RequestParam(value = "file", required = false)
		MultipartFile multipartFile) {
		logger.info("iconUpload called");
		
		UploadMsg uploadMsg = new UploadMsg();
		PictureUploadMsg pictureUploadMsg = new PictureUploadMsg();
		
		if (multipartFile != null) {
			pictureUploadMsg = pictureService.uploadPic(multipartFile);
			uploadMsg.setMessage(pictureUploadMsg.getMessage());
			if (pictureUploadMsg.getError()) {
				uploadMsg.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				uploadMsg.setResult(pictureUploadMsg.getUrl());
			} else {
				uploadMsg.setCode(HttpServletResponse.SC_OK);
				uploadMsg.setResult(pictureUploadMsg.getUrl());
			}
		}
		
		return uploadMsg;
	}
	
	@ResponseBody
	@RequestMapping(value = "/api/uploadurl", method = RequestMethod.POST)
	public UploadMsg iconUpload(@RequestParam String image,
			HttpSession session) {
		logger.info("iconUpload called");
		
		UploadMsg uploadMsg = new UploadMsg();
		PictureUploadMsg pictureResult = new PictureUploadMsg();
		
		if (image != null) {
			pictureResult = pictureService.uploadPic(image);
			uploadMsg.setMessage(pictureResult.getMessage());
			if (!pictureResult.getError()) {
				uploadMsg.setCode(HttpServletResponse.SC_OK);
				uploadMsg.setResult(pictureResult.getUrl());
			} else {
				uploadMsg.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				uploadMsg.setResult(pictureResult.getUrl());
			}
			session.setAttribute("icon", pictureResult.getUrl());
		}
		
		return uploadMsg;
	}
}
